/**
 * Created by wangshaohua on 2018/1/13.
 */
moduleLearningMap.controller("LearningMapQuizExerciseDetail", function (LanguageService, $$CambioConfig, UploadFileService, $scope, $log, $state, $stateParams, GeneralResource, LoadingService, ConstantService, DialogService, LearningMapQuizExerciseResource, LearningMapExerciseResource) {
    initPage($scope);
    $scope.$on("$viewContentLoaded", function () {
        //$scope.reset();
        pageOnLoad();
        ConstantService.addState($state.current, true, LanguageService.language('学习地图测试课程详细'));
        $scope.learningMapCourseId = $stateParams.learningMapCourseId;
        $scope.learningMapExerciseId = $stateParams.learningMapExerciseId;
        $scope.loadDetail();
        $scope.selectTab('tabInfo');
    });

    $scope.currentTabId = 0;
    $scope.selectTab = function (tabId) {
        if (tabId === 'tabInfo') {

            $scope.currentTabId = tabId;
        }
        if (tabId === 'tabExerciseQuickConfig' && $scope.learningMapExerciseId) {
            $scope.currentTabId = tabId;
        }
        if (tabId === 'tabExerciseConfig' && $scope.learningMapExerciseId) {
            $scope.currentTabId = tabId;
        }
    };

    // ------------------------------------------------------------------------------------------------------

    $scope.loadDetail = function () {
        if ($scope.learningMapExerciseId) {
            //LoadingService.show();
            LearningMapExerciseResource.findById({id: $scope.learningMapExerciseId}, {}, function (queryResult) {
                $log.debug("查询结果", queryResult.data);
                $scope.learningMapExerciseDetail = queryResult.data;
                //LoadingService.hide();
            });
        } else {
            $scope.learningMapExerciseDetail = {
                exerciseId: $scope.learningMapExerciseId,
                courseId: $scope.learningMapCourseId,
                type: 'EXAMINATION',
                picture: LearningMapTemplateUtils.findExercise('EXAMINATION').picture
            };
        }
    };

    $scope.saveExercise = function () {

        Alert.confirm(function () {
            if ($scope.learningMapExerciseId) {
                LearningMapQuizExerciseResource.update({}, $scope.learningMapExerciseDetail, function () {
                    $log.debug("查询结果", queryResult.data);
                    //$scope.learningMapCourseDetail = queryResult.data;
                    Alert.success();
                    $scope.loadDetail();
                    //LoadingService.hide();
                });
            } else {
                LearningMapQuizExerciseResource.save({}, $scope.learningMapExerciseDetail, function (queryResult) {
                    $log.debug("查询结果", queryResult.data);
                    $scope.learningMapExerciseId = queryResult.data.value;
                    $state.go('sz.learningMapQuizExerciseDetail', {
                        learningMapExerciseId: $scope.learningMapExerciseId,
                        learningMapCourseId: $scope.learningMapCourseId
                    });
                    Alert.success();
                    //LoadingService.hide();
                });
            }
        })
    }

    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------
    function checkWBJson(rawJson) {
        var first = rawJson[0];
        /** @namespace first.Answer */
        /** @namespace first.Title */
        return (first && first.Title && first.Type && first.A && first.B && first.Answer);
    }

    function addAttribute(answer, itemCode, sort, content, currentTopic) {
        if (StringUtils.isNlOrUndOrEmpty(content)) {
            return;
        }
        var currentAttribute = {};
        currentAttribute.sort = sort;
        currentAttribute.score = answer.includes(itemCode) ? 1 : 0;
        currentAttribute.content = content;
        currentTopic.attributes.push(currentAttribute);
    }

    function jsonToQuizTopicWB(rawJson) {
        var topicList = [];
        rawJson.forEach(function (rawQuizTopic, index) {
            var currentTopic = {};
            currentTopic.itemCode = index + 1;
            if (parseInt(rawQuizTopic['Type']) === 0) {
                currentTopic.type = 'SELECT'
            } else {
                currentTopic.type = 'CHECKBOX_BOOLEAN';
            }
            currentTopic.content = rawQuizTopic['Title'];
            currentTopic.attributes = [];
            addAttribute(rawQuizTopic.Answer, 'A', 1, rawQuizTopic.A, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'B', 2, rawQuizTopic.B, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'C', 3, rawQuizTopic.C, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'D', 4, rawQuizTopic.D, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'E', 5, rawQuizTopic.E, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'F', 6, rawQuizTopic.F, currentTopic);
            topicList.push(currentTopic);
        });
        return topicList;
    }

    /**
     * "[{
     *      "Title":"“倒拿或乱用工具会导致事故”，这种说法正确吗？",
     *      "Type":"0",
     *      "question_knowledge":"正确",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":"1",
     *      "A":"正确",
     *      "B":"错误",
     *      "Answer":"A"
     *  },{
     *      "Title":"文中，梯子、梯凳有几条安全须知？",
     *      "Type":"0",
     *      "question_knowledge":"9条",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":
     *      "1",
     *      "A":"9条",
     *      "B":"6条",
     *      "C":"7条",
     *      "D":"8条",
     *      "Answer":"A"
     *  }]"
     * @param workbook
     */
    $scope.readWB = function (workbook) {
        /* DO SOMETHING WITH workbook HERE */
        $log.debug(workbook);
        var rawJson = XLS.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        $log.debug("excel数据", rawJson);
        if (!checkWBJson(rawJson)) {
            Alert.error(LanguageService.language('数据格式错误!'));
        } else {
            var topicList = jsonToQuizTopicWB(rawJson);
            $log.debug("转换后数据", topicList);
            //$scope.currentQuizTopicGroup.gaugeTopics = topicList;
            $scope.learningMapExerciseDetail.topics = topicList;
            $scope.$apply();
        }
    };


    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------

    $scope.uploadExerciseImage = function ($files) {
        if ($files && $files[0]) {
            UploadFileService.uploadFile($files[0], $$CambioConfig.UPLOAD_URL, 'IMG', $scope).then(function (o) {
                $scope.learningMapExerciseDetail.picture = o.id;
            });
        }
    };
});